package zhieasy.cn.xpu_helper.security.filter;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import zhieasy.cn.model.common.WechatUser;
import zhieasy.cn.xpu_helper.security.detailservice.WechatDetailsService;
import zhieasy.cn.xpu_helper.security.exception.TokenException;
import zhieasy.cn.xpu_helper.security.handler.LoginFailureHandler;
import zhieasy.cn.xpu_helper.security.utils.IPUtils;
import zhieasy.cn.xpu_helper.security.utils.JwtUtils;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * @author DaHang
 * @date 2020/8/13 21:45
 */
@Slf4j
@Component
public class CheckTokenFilter extends OncePerRequestFilter {

    @Value("#{'${zhieasy.permitUrlList}'.split(',')}")
    private List<String> permitUrlList;


    @Autowired
    private LoginFailureHandler loginFailureHandler;
    @Autowired
    private JwtUtils jwtUtils;
    @Autowired
    private WechatDetailsService wechatDetailsService;


    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
                                    FilterChain filterChain) throws ServletException, IOException {
        //获取到请求路劲
        String url = request.getRequestURI();
        String ipAddress = IPUtils.getClientIpAddress(request);
        //如果是登录的路径
        if (isPermitUrl(permitUrlList,url)){
            //我啥也不干
            log.info("Pass URL={}", url);
        } else{
            //否则得要验证token
            log.info("Need validate token URL={}", url);
            validateToken(request);
        }
        filterChain.doFilter(request, response);
    }

    private boolean isPermitUrl(List<String> urlList, String url){
        if (url.isEmpty())
            return false;
        for (String permitUrl: urlList) {
            //如果有匹配成功正则表达式的或者相等的，就返回true
            if (url.matches(permitUrl) || url.equals(permitUrl))
                return true;
        }
        return false;
    }

    /**
     * 验证token
     * @param request
     */
    private void validateToken(HttpServletRequest request) {

        //获取前端传来的token
        String token = request.getHeader("token");
        if ("ningdali".equals(token)){
            WechatUser wechatUser ;
            wechatUser = wechatDetailsService.loadUserByOpenId("ningdali");
            if (wechatUser == null) {
                throw new TokenException("token验证失败!");
            }
            UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(wechatUser, null,
                wechatUser.getAuthorities());
            //AuthorityUtils.commaSeparatedStringToAuthorityList("");
            authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
            SecurityContextHolder.getContext().setAuthentication(authentication);
            return;
        }
        //解析token，获取用户名
        String username = jwtUtils.getUsernameFromToken(token);
        //如果token或者用户名为空的话，不能通过认证
        if (StringUtils.isBlank(token) || StringUtils.isBlank(username)) {
            throw new TokenException("token验证失败!");
        }

        WechatUser wechatUser ;
        //从token拿用户信息，不用管这个人是不是第一次一次登录了
        String openId = jwtUtils.getUsernameFromToken(token);
        wechatUser = wechatDetailsService.loadUserByOpenId(openId);
        if (wechatUser == null) {
            throw new TokenException("出现了token正确，但是数据库没有这个人的情况!");
        }
        wechatUser.setSessionKey(jwtUtils.getString(token,"sessionKey"));

        UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(wechatUser, null,
            wechatUser.getAuthorities());
        //AuthorityUtils.commaSeparatedStringToAuthorityList("");
        authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));

//        //不知道是啥，慢慢研究
//        UsernamePasswordAuthenticationToken authentication = new
//            UsernamePasswordAuthenticationToken(wechatUser, null, wechatUser.getAuthorities());
//
//        authentication.setDetails(new
//            WebAuthenticationDetailsSource().buildDetails(request));
        //设置为已登录
        SecurityContextHolder.getContext().setAuthentication(authentication);
    }
    /**
        //验证验证码
     private void validate(HttpServletRequest request) {
        //1.获取登录请求的验证码
        String inputCode = request.getParameter("code");
        //2.获取Session中的验证码
        String code =
            (String) request.getSession().getAttribute(UserController.SESSION_KEY);
        //3.判断验证码是否为空
        if (StringUtils.isBlank(inputCode)) {
            throw new ImageCodeException("验证码不能为空!");
        }
        //4.判断验证码是否相等
        if (!inputCode.equalsIgnoreCase(code)) {
            throw new ImageCodeException("验证码输入错误!");
        }
    }
     */
}
